//
//  MasterViewController.m
//  TextApplication
//
//  Created by dllo on 16/8/27.
//  Copyright © 2016年 yh. All rights reserved.
//

#import "MasterViewController.h"
#import "TextView.h"
#import "MasterCollectionViewCell.h"
#import "TAMacro.h"
#import "ZWYNetTool.h"
#import "MasterModel.h"
#import "UIImageView+WebCache.h"
#import "MasterDetailViewController.h"
#import "MBProgressHUD.h"
#import "MJRefresh.h"

#import "MasterFirst.h"
#import "MasterData.h"
#import "MasterItems.h"
#import "MasterImage.h"

#import "SearchViewController.h"

@interface MasterViewController () <UICollectionViewDataSource, UICollectionViewDelegate, UITableViewDataSource, UITableViewDelegate, UIScrollViewDelegate, UITextFieldDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *collectArray;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *tableArray;
@property (nonatomic, strong) UIScrollView *backScrollView;
@property (nonatomic, strong) UIButton *right;
@property (nonatomic, strong) UIButton *left;
@property (nonatomic, strong) UIButton *secRight;

@property (nonatomic, copy) NSString *str3;

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, copy) NSString *str;

@property (nonatomic, strong) UIButton *grayBackButton;
@property (nonatomic, strong) UITextField *searchTextField;

@property (nonatomic, strong) MasterFirst *first;
@end

@implementation MasterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.barTintColor = [UIColor blackColor];
    self.page = 1;
    [self createTop];

    [self createCollectionView];
    [self createTableView];
    [self createSearch];

    self.collectArray = [NSMutableArray array];
    [self createCollectionViewData];
    
}

- (void)createTableView {
    self.backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 0)]; // 设置滚动范围大于scrollView大小就可以滚动
    self.backScrollView.delegate = self;
    self.backScrollView.contentSize = CGSizeMake(0, HEIGHT - 100);
    self.backScrollView.backgroundColor = [UIColor blackColor];
    self.backScrollView.alpha = 0.5;
    [self.view addSubview:self.backScrollView];
    self.tableArray = [NSArray array];
    self.tableArray = @[@"默认推荐", @"最多推荐", @"最受欢迎", @"最新加入", @"最新推荐"];
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 250) style:UITableViewStylePlain];
    self.tableView.scrollEnabled = NO;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.rowHeight = 50;
    [self.backScrollView addSubview:self.tableView];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"tableReuse"];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"tableReuse"];
    cell.backgroundColor = [UIColor whiteColor];
    cell.textLabel.text = self.tableArray[indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        self.page = 1;
        self.str3 = @"";
        [self createCollectionViewData];
    } else if (indexPath.row == 1) {
        self.page = 1;
        self.str3 = @"&orderby=goods_sum";
        [self createCollectionViewData];
    } else if (indexPath.row == 2) {
        self.page = 1;
        self.str3 = @"&orderby=followers";
        [self createCollectionViewData];
    } else if (indexPath.row == 3) {
        self.page = 1;
        self.str3 = @"&orderby=reg_time";
        [self createCollectionViewData];
    } else if (indexPath.row == 4) {
        self.page = 1;
        self.str3 = @"&orderby=action_time";
        [self createCollectionViewData];
    }
    [UIView animateWithDuration:1 animations:^{
        self.backScrollView.frame = CGRectMake(0, 0, WIDTH, 0);
        [self.view addSubview:self.backScrollView];
    }];
    [self createCollectionViewData];
    
    self.right = [TextView createButtonWithImage:[UIImage imageNamed:@"21"]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.right];
    [self.right addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
}
// 下拉刷新
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    if (self.collectionView.contentOffset.y < 0) {
        self.page = 1;
//        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
//        hud.label.text = NSLocalizedString(@"loading", @"HUD loading title");
//        NSLog(@"下拉刷新");
//        [hud hideAnimated:YES afterDelay:1];
        [self createCollectionViewData];
//        [self.collectionView reloadData];
    }
}

// 上拉加载
- (void)upLoad {
      self.collectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self createCollectionViewData];
        [self.collectionView.mj_footer endRefreshing];
    }];
}

- (void)handleUrl {
    NSString *str1 = @"http://mobile.iliangcang.com/user/masterList/?";
    NSString *str4 = @"&page=";
    NSString *str2 = @"&count=20&app_key=iPhone&v=3.0.0&sig=254F2CCC-7E43-4833-A27D-7D12702F5981";
    if (self.str3.length == 0) {
        self.str = [[[str1 stringByAppendingString:str4] stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]]stringByAppendingString:str2];
        NSLog(@"%@", self.str3);
        
    } else {
        self.str = [[[[str1 stringByAppendingString:self.str3] stringByAppendingString:str4] stringByAppendingString:[NSString stringWithFormat:@"%ld", self.page]] stringByAppendingString:str2];
    }


}
- (void)createCollectionViewData {
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.label.text = NSLocalizedString(@"loading", @"HUD loading title");

    [self handleUrl];
    NSDictionary *headDic = @{@"Host": @"mobile.iliangcang.com", @"Proxy-Connection": @"keep-alive", @"Accept": @"*/*", @"Accept-Language": @"zh-Hans-CN;q=1, en-CN;q=0.9", @"Connection": @"keep-alive", @"User-Agent": @"iLiangCang/3.0.0 (iPhone; iOS 9.2.1; Scale/2.00) Paros/3.2.13"};
       [ZWYNetTool GET:self.str andBody:nil andHeader:headDic andResponse:ZWYJSON andSuccessBlock:^(id result) {
        if (self.page == 1) {
            self.collectArray = [NSMutableArray array];
        }
        NSArray *array = result[@"data"][@"items"];
        for (NSDictionary *dic in array) {
            MasterModel *master = [MasterModel modelWithDic:dic];
            [self.collectArray addObject:master];
        }
           if (self.collectArray.count != 0) {
               [hud hideAnimated:YES afterDelay:0.5];
           }
        [self.collectionView reloadData];
        self.page = self.page + 1;
    } andFailureBlock:^(NSError *error) {
    }];
}

- (void)createTop {
    self.title = @"达人";
    
    self.view.backgroundColor = [UIColor yellowColor];
    UIButton *left = [TextView createButtonWithImage:[UIImage imageNamed:@"19"]];
    [left addTarget:self action:@selector(searchAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:left];
    
    self.right = [TextView createButtonWithImage:[UIImage imageNamed:@"21"]];
    [self.right addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.right];
}

- (void)searchAction:(UIButton *)button {
    [UIView animateWithDuration:0.5 animations:^{
        self.grayBackButton.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
        self.searchTextField.frame = CGRectMake(10, 0, WIDTH - 20, 40);
    }];
}


- (void)createSearch {
    self.grayBackButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.grayBackButton.frame = CGRectMake(0, 0, WIDTH, 0);
    self.grayBackButton.backgroundColor = [UIColor blackColor];
    self.grayBackButton.alpha = 0.5;
    [self.grayBackButton addTarget:self action:@selector(grayButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.grayBackButton];
    self.searchTextField = [[UITextField alloc] initWithFrame:CGRectMake(10, 0, WIDTH - 20, 0)];
    self.searchTextField.delegate = self;
    self.searchTextField.placeholder = @"                                 search";
    self.searchTextField.clearsOnBeginEditing = NO;
    self.searchTextField.contentVerticalAlignment = UIControlContentHorizontalAlignmentCenter;
    [self.searchTextField setValue:[UIColor colorWithWhite:0.211 alpha:1.000] forKeyPath:@"_placeholderLabel.textColor"];

    // 设置textField的右侧的清除键
    self.searchTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.searchTextField.backgroundColor = [UIColor whiteColor];
    self.searchTextField.keyboardType = UIKeyboardTypeDefault;
    self.searchTextField.returnKeyType = UIReturnKeySearch;
    [self.grayBackButton addSubview:self.searchTextField];

}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    searchVC.textFieldStr = self.searchTextField.text;
    [self.navigationController pushViewController:searchVC animated:YES];
    [self.searchTextField resignFirstResponder];
    [UIView animateWithDuration:0.5 animations:^{
        self.grayBackButton.frame = CGRectMake(0, 0, WIDTH, 0);
        self.searchTextField.frame = CGRectMake(10, 0, WIDTH - 20, 0);
    }];
    return YES;
}

- (void)grayButtonAction:(UIButton *)button {
    [UIView animateWithDuration:0.5 animations:^{
        self.grayBackButton.frame = CGRectMake(0, 0, WIDTH, 0);
        self.searchTextField.frame = CGRectMake(10, 0, WIDTH - 20, 0);
    }];
    // 回收键盘
    [self.searchTextField resignFirstResponder];
}

- (void)rightClick:(UIButton *)button {
    [UIView animateWithDuration:1 animations:^{
        self.backScrollView.frame = CGRectMake(0, 0, WIDTH, HEIGHT );
        [self.view addSubview:self.backScrollView];
    }];
    self.secRight = [TextView createButtonWithImage:[UIImage imageNamed:@"6"]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.secRight];
    [self.secRight addTarget:self action:@selector(secRightClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)secRightClick:(UIButton *)button {
    
    [UIView animateWithDuration:1 animations:^{
        self.backScrollView.frame = CGRectMake(0, 0, WIDTH, 0);
        [self.view addSubview:self.backScrollView];
    }];
    self.right = [TextView createButtonWithImage:[UIImage imageNamed:@"21"]];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.right];
    [self.right addTarget:self action:@selector(rightClick:) forControlEvents:UIControlEventTouchUpInside];
}


- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(WIDTH / 3, 170);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 110) collectionViewLayout:layout];
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.view addSubview:self.collectionView];
    
    [self.collectionView registerClass:[MasterCollectionViewCell class] forCellWithReuseIdentifier:@"reuse"];

}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.collectArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    [self upLoad];
    MasterCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    cell.nameLabel.text = [self.collectArray[indexPath.row] username];
    cell.jobLabel.text = [self.collectArray[indexPath.row] duty];
    [cell.picImageView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", [self.collectArray[indexPath.row] user_images][@"orig"]]]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    MasterDetailViewController *detailVC = [[MasterDetailViewController alloc] init];
    detailVC.netID = [self.collectArray[indexPath.row] uid];
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
